import * as _ from "lodash-es";
import { Observable, filter, from, mergeMap, shareReplay } from "rxjs";
import { WASSheetCaller } from "../WASSheetCaller";
import { ICellRaw, readRowObs } from "./util";

/**
 * 读取表头数据方便进行对象映射
 */
export class TitleReader
{
    private titleRawObs?: Observable<ICellRaw>

    /**
     * 
     * @param sheetCaller 
     * @param sheetName 
     * @param titleColIndex 最大扫描到第几列, 默认50
     * @param titleRowStartIndex 哪行作为表头, 默认1
     * @param [titleRowEndIndex=0] 往上扫描表头数据，默认0就是不扫描
     */
    constructor(
        private sheetCaller: WASSheetCaller,
        private sheetName: string,
        private titleColIndex: number = 50,
        private titleRowStartIndex: number = 1,
        private titleRowEndIndex: number = 0,
    ){}

    /**
     * 获取原始表头数据
     * 
     * 会缓存
     * @returns
     */
    getTitleRawObs()
    {
        if(!this.titleRawObs)
        {
            this.titleRawObs = this.readTitleObs().pipe(
                shareReplay()
            )
        }
        return this.titleRawObs
    }

    /**
     * 清除缓存
     */
    cleanCache()
    {
        this.titleRawObs = undefined
    }

    private readTitleObs()
    {
        let loopObs = from(_.range(this.titleRowStartIndex, this.titleRowEndIndex))
        return loopObs.pipe(
            mergeMap(rowStartIndex =>
                readRowObs(
                    this.sheetCaller, this.sheetName,
                    rowStartIndex, rowStartIndex,
                    1, this.titleColIndex
                ).pipe(
                    filter(v => !!v.value)
                ),
            1)
        )
    }
}
